package com.nl.controller.common.redis;

import java.util.ArrayList;
import java.util.List;

import com.nl.controller.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import redis.clients.jedis.Jedis;

public class SingleRedis {
    private static Logger LOG = LoggerFactory.getLogger(SingleRedis.class);
    public List<Jedis> redisCLuster(String str) {
        List<String> list = new ArrayList<String>();
        list = StringUtil.split(str, "%_%");
        List<Jedis> jList= new ArrayList<Jedis>();
        for(String redisCfg : list){
            try{
                String[] sStr = redisCfg.split(":");
                Jedis jedis = null;
                if (sStr.length == 2) {
                    jedis  = conRedis(sStr[0], Integer.parseInt(sStr[1]));
                } else if (sStr.length == 3) {
                    jedis = conRedis(sStr[0], Integer.parseInt(sStr[1]), sStr[2]);
                }
                String info = jedis.info();
                if (!info.contains("role:master")) {
                    LOG.warn("this node is not master!");
                    jedis.close();
                    continue;
                }
                jList.add(jedis);  
            } catch(Exception e){
                e.printStackTrace();
            }
        }
        return jList;
    } 
    
    public Jedis conRedis(String ip, int port , String password){
        Jedis jedis = new Jedis(ip, port, 2000);
        jedis.auth(password);
        return jedis;
    }
    
    public Jedis conRedis(String ip, int port){
        Jedis jedis = new Jedis(ip, port, 2000);
        return jedis;
    }
    
  
}
